using System;
using System.Collections.Generic;
using Castle.ActiveRecord;
using Newtonsoft.Json;

namespace Karma.Framework.Core.Metadata.Mapping
{
    [ActiveRecord("[AggregateField]")]
    public class AggregateField : Field
    {
        [JoinedKey]
        public override Int64 Id { get; set; }

        [Property(NotNull = true)]
        public string EntityName { get; set; }

        public virtual Query Query
        {
            get { return (_Query == null || _Query.Count == 0 ? null : _Query[0]); }
            set
            {
                if (_Query == null)
                {
                    _Query = new List<Query> { value };
                }
                _Query[0] = value;
            }
        }

        [JsonIgnore]
        [HasMany(ColumnKey = "[AggregateField]", Cascade = ManyRelationCascadeEnum.All,
            Lazy = false, Table = "[Query]")]
        protected virtual IList<Query> _Query { get; set; }

        public virtual Query SearchQuery
        {
            get { return (_Query == null || _Query.Count != 2 ? null : _Query[1]); }
            set
            {
                if (_Query == null)
                {
                    throw new InvalidOperationException("primero especifique el atributo Query del AggregateList");
                }
                if (_Query.Count == 1)
                {
                    _Query.Add(value);
                }
                _Query[1] = value;
            }
        }

    }
}